﻿using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace IEBrowser
{



    public partial class Form1 : Form
    {

        //
        public Form1()
        {
            InitializeComponent();
            SetIE(IeVersion.强制IE11);
            this.tabControl1.DoubleClick += TabControl1_DoubleClick;//双击关闭

            //首页
            this.webBrowser1.NewWindow += WebBrowser1_NewWindow;//新窗口事件
            this.webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;//加载完成事件
            this.webBrowser1.Navigate("http://localhost/psd.html");

            //MessageBox.Show("当前IE版本:" + GetBrowserVersion());
            //MessageBox.Show(this.webBrowser1.Version.ToString());
        }



        private void WebBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true; //防止IE弹窗；
            WebBrowser web1 = (WebBrowser)tabControl1.SelectedTab.Controls[0];//获取当前活动选项卡上的WebBrowser
            string url = web1.StatusText;//获取鼠标点击的URL

            //新建选项卡
            TabPage newPage = new TabPage
            {
                Name = "newPage",
                Text = "加载中",

            };


            //新建WebBrowser
            WebBrowser newWebBrowser = new WebBrowser
            {
                Name = "newWebBrowser",
                Dock = DockStyle.Fill,
                ScriptErrorsSuppressed = true //屏蔽脚本错误后
            };
            //WebBrowser绑定事件
            newWebBrowser.DocumentCompleted += WebBrowser1_DocumentCompleted;
            newWebBrowser.NewWindow += WebBrowser1_NewWindow;

            newPage.Controls.Add(newWebBrowser);//新WebBrowser添加到新选项卡  
            tabControl1.TabPages.Add((TabPage)(newPage)); // 新选项卡添加到TabControl         
            tabControl1.SelectTab(newPage);//新选项卡位活动选项卡


            newWebBrowser.Url = new Uri(url);   //转到网站

        }


        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser wb = sender as WebBrowser;
            String TitleStr = wb.DocumentTitle;
            if ((wb.Parent.Text == "首页" || wb.Parent.Text == "加载中") && TitleStr != "")
            {
                wb.Parent.Text = TitleStr;
                //MessageBox.Show( wb.Document.GetElementsByTagName("div").Count  + "");
                // MessageBox.Show(wb.Document.GetElementsByTagName("div")[0].InnerText);
            }
        }

        private void TabControl1_DoubleClick(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex > 0)
                tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
        }


        /// <summary>  
        /// 修改注册表信息来兼容当前程序  
        ///   
        /// </summary>  
        static void SetWebBrowserFeatures(int ieVersion)
        {
            // don't change the registry if running in-proc inside Visual Studio  
            if (LicenseManager.UsageMode != LicenseUsageMode.Runtime)
                return;
            //获取程序及名称  
            var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            //得到浏览器的模式的值  
            UInt32 ieMode = GeoEmulationModee(ieVersion);
            var featureControlRegKey = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\";
            //设置浏览器对应用程序（appName）以什么模式（ieMode）运行  
            Registry.SetValue(featureControlRegKey + "FEATURE_BROWSER_EMULATION",
                appName, ieMode, RegistryValueKind.DWord);
            // enable the features which are "On" for the full Internet Explorer browser  
            //不晓得设置有什么用  
            Registry.SetValue(featureControlRegKey + "FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION",
                appName, 1, RegistryValueKind.DWord);


            //Registry.SetValue(featureControlRegKey + "FEATURE_AJAX_CONNECTIONEVENTS",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_GPU_RENDERING",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_WEBOC_DOCUMENT_ZOOM",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_NINPUT_LEGACYMODE",  
            //    appName, 0, RegistryValueKind.DWord);  
        }
        /// <summary>  
        /// 获取浏览器的版本  
        /// </summary>  
        /// <returns></returns>  
        static int GetBrowserVersion()
        {
            int browserVersion = 0;
            using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer",
                RegistryKeyPermissionCheck.ReadSubTree,
                System.Security.AccessControl.RegistryRights.QueryValues))
            {
                var version = ieKey.GetValue("svcVersion");
                if (null == version)
                {
                    version = ieKey.GetValue("Version");
                    if (null == version)
                        throw new ApplicationException("Microsoft Internet Explorer is required!");
                }
                int.TryParse(version.ToString().Split('.')[0], out browserVersion);
            }
            //如果小于7  
            if (browserVersion < 7)
            {
                throw new ApplicationException("不支持的浏览器版本!");
            }
            return browserVersion;
        }
        /// <summary>  
        /// 通过版本得到浏览器模式的值  
        /// </summary>  
        /// <param name="browserVersion"></param>  
        /// <returns></returns>  
        static UInt32 GeoEmulationModee(int browserVersion)
        {
            UInt32 mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode.   
            switch (browserVersion)
            {
                case 7:
                    mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.   
                    break;
                case 8:
                    mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.   
                    break;
                case 9:
                    mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.                      
                    break;
                case 10:
                    mode = 10000; // Internet Explorer 10.  
                    break;
                case 11:
                    mode = 11000; // Internet Explorer 11  
                    break;
            }
            return mode;
        }


        /// <summary>
        /// 定义IE版本的枚举
        /// </summary>
        private enum IeVersion
        {
            强制IE11,//11001 (0x2EDF) Internet Explorer 11. Webpages are displayed in IE11 Standards mode, regardless of the !DOCTYPE directive
            标准IE11,//11000 (0x2AF8) ：Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode
            强制ie10,//10001 (0x2711) Internet Explorer 10。网页以IE 10的标准模式展现，页面!DOCTYPE无效
            标准ie10,//10000 (0x02710) Internet Explorer 10。在IE 10标准模式中按照网页上!DOCTYPE指令来显示网页。Internet Explorer 10 默认值。
            强制ie9,//9999 (0x270F) Windows Internet Explorer 9. 强制IE9显示，忽略!DOCTYPE指令
            标准ie9,//9000 (0x2328) Internet Explorer 9. Internet Explorer 9默认值，在IE9标准模式中按照网页上!DOCTYPE指令来显示网页。
            强制ie8,//8888 (0x22B8) Internet Explorer 8，强制IE8标准模式显示，忽略!DOCTYPE指令
            标准ie8,//8000 (0x1F40) Internet Explorer 8默认设置，在IE8标准模式中按照网页上!DOCTYPE指令展示网页
            标准ie7//7000 (0x1B58) 使用WebBrowser Control控件的应用程序所使用的默认值，在IE7标准模式中按照网页上!DOCTYPE指令来展示网页
        }

        /// <summary>
        /// 设置WebBrowser的默认版本
        /// </summary>
        /// <param name="ver">IE版本</param>
        private void SetIE(IeVersion ver)
        {
            string productName = AppDomain.CurrentDomain.SetupInformation.ApplicationName;//获取程序名称

            object version;
            switch (ver)
            {
                case IeVersion.标准ie7:
                    version = 0x1B58;
                    break;
                case IeVersion.标准ie8:
                    version = 0x1F40;
                    break;
                case IeVersion.强制ie8:
                    version = 0x22B8;
                    break;
                case IeVersion.标准ie9:
                    version = 0x2328;
                    break;
                case IeVersion.强制ie9:
                    version = 0x270F;
                    break;
                case IeVersion.标准ie10:
                    version = 0x02710;
                    break;
                case IeVersion.强制ie10:
                    version = 0x2711;
                    break;
                case IeVersion.强制IE11:
                    version = 0x2EDF;
                    break;
                case IeVersion.标准IE11:
                    version = 0x2AF8;
                    break;
                default:
                    version = 0x1F40; //1ie8
                    break;
            }

            RegistryKey key = Registry.CurrentUser;
            RegistryKey software = key.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\" + productName);
            if (software != null)
            {
                software.Close();
                software.Dispose();
            }
            RegistryKey wwui =key.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
            //该项必须已存在
            if (wwui != null) wwui.SetValue(productName, version, RegistryValueKind.DWord);
        }

    }




}